import Vue from 'vue'
import Router from 'vue-router'
import store from "@/store/index.js";
import initAsyncRouter from '@/router/initAsyncRouter'

import {
	constantRouterMap
} from './router.config.js'

Vue.use(Router)

const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
// push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
// replace
Router.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}


const router = new Router({
  mode:'history',
	routes: constantRouterMap,
})

/**
 * 路由守卫
 * 
 * @param {to} 将要去的路由
 * @param {from} 出发的路由
 * @param {next} 执行下一步
 */
router.beforeEach((to, from, next) => {

  getTargetComponent(to.matched[0]).then(target => {
    navigate(target, to, next)
  }).catch(err => {
    console.log(new Error('function getTargetComponent error!'))
    console.log(err)
  })

})


function getTargetComponent (argu) {
  return new Promise((resolve, reject) => {
    try {
      if (!argu) {
        resolve(null)
      }
      if (typeof argu.components.default === 'function') {
        argu.components.default().then(res => {
          resolve(res.default.name)
        }).catch(error => {
          reject(error)
        })
      } else {
        resolve(argu.components.default.name)
      }
    } catch (error) {
      reject(error)
    }
  })
}

async function navigate (target, to, next) {
  if ((target === 'home' || target === null) && !store.state.app.asyncRoutesCompleted) {
    initAsyncRouter().then(res => {
      next(router.resolve(to).route.fullPath)
    }).catch(err => {
      console.log("出现异常：", err)
      next('/login')
    })

  } else {
    // 路由出错跳转
    if(to.matched.length == 0) {
      next({
        path: '/404',
      })
    }
    // 登录跳转
    if(to.meta.requireAuth) {
      
      // 1. 检查 是否有 token
      let token = localStorage.getItem("token")
      
      // 1.1 有 token 放行
      if(token) {
        next()
      } else {  // 1.2. 无 token 去登录
        next('/login')
      }
    } else {
      next()
    }
  }
}

export default router